package com.yq.activemq.helloworld;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Receiver {

    /**
     * 消息服务器地址
     */
    public static final String BROKER_URL = "tcp://localhost:61616";

    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        receiver.receiveMessage();
    }

    private void receiveMessage() {
        Connection connection = null;
        Session session = null;
        MessageConsumer consumer = null;

        try {
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
            connection = connectionFactory.createConnection();
            // Boolean.FALSE表示本次会话不开启事务管理,假如需要开启事务管理,将其改为Boolean.TRUE
            // 同时需要在发送消息后添加session.commit(),否则,消息是不会被提交的.
            // Session.AUTO_ACKNOWLEDGE表示消息确认机制
            // AUTO_ACKNOWLEDGE:自动确认
            // CLIENT_ACKNOWLEDGE:客户端确认
            // SESSION_TRANSACTED:事务确认,如果使用事务推荐使用该确认机制
            // AUTO_ACKNOWLEDGE:懒散式确认,消息偶尔不会被确认,也就是消息可能会被重复发送,但发生的概率很小.
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);

            Queue destination = session.createQueue("myQueue");

            consumer = session.createConsumer(destination);
            // //在消息接收端,需要开启连接,否则一样无法获取消息.
            connection.start();

            Message message = consumer.receive();

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println(textMessage.getText());
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (consumer != null) {
                    consumer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

    }
}
